import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Card,
  Button,
  Form,
  Row,
  Col,
  Input,
  Spin,
  BackTop,
  Select,
  // DatePicker,
  notification,
  Icon,
  Popover,
  Affix,
} from 'antd';
import { Map } from 'react-amap';
import Geolocation from 'react-amap-plugin-geolocation';

import { refitFieldDecoratorOption, refitCommonData } from '../../../utils/tools';
// import FooterToolbar from '../../../components/FooterToolbar';
import UIPoiPicker from '../../../customComponents/AMap/UIPoiPicker';
import UIPositionPicker from '../../../customComponents/AMap/UIPositionPicker';
import styles from './BasicInfo.less';

// const { TextArea } = Input;
const FormItem = Form.Item;
// const { MonthPicker } = DatePicker;

const fieldLabels = {
  intuserid: '用户ID',
  chvmname: '服务站名',
  chvrealname: '站长姓名',
  phone: '联系电话',
  emergencyPhone: '紧急联系电话',
  idCard: '身份证号',
  bankName: '开户银行',
  creditCardNumber: '银行卡号',
  payTheFees: '是否缴费',
  procurement: '开启采购',
  shopSwitch: '店铺开关',
  lineId: '配送线路',
  show: '是否显示',
  area: '省份-城市-县区',
  address: '详细地址',
  longitude: '经度',
  latitude: '纬度',
  frontPapersImage: '正面证件照',
  contraryPapersImage: '反面证件照',
  map: '地点标记（移动地图后，中心点坐标将被选取，详细地址与经维护信息将自动获取填充）',
};

const pluginProps = {
  enableHighAccuracy: true,
  timeout: 10000,
  showButton: true,
};

@connect(({ saler, global, loading }) => ({
  saler,
  global,
  loading: loading.models.saler,
}))
@Form.create()
class BasicInfo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      // width: '100%',
      metaData: {},
      dataLoading: true,
      saving: false,
      mapAddress: '',
      // mapPosition: '',
      mapLatitude: 0,
      mapLongitude: 0,
    };
  }

  componentDidMount() {
    this.isMountedFlag = true;

    const { match } = this.props;
    const { params } = match;
    const { id: salerId } = params;

    this.loadData(salerId);
  }

  onChangeAddress = e => {
    const { value: v } = e.target;

    this.setState({ mapAddress: v });
  };

  onChangeLongitude = e => {
    const { value: v } = e.target;

    this.setState({ mapLongitude: v });
  };

  onChangeLatitude = e => {
    const { value: v } = e.target;

    this.setState({ mapLatitude: v });
  };

  loadData = id => {
    const { dispatch } = this.props;

    this.setState({ dataLoading: true }, () => {
      dispatch({
        type: 'saler/get',
        payload: {
          productId: id,
        },
      }).then(() => {
        if (this.isMountedFlag) {
          const {
            saler: {
              data: { data },
            },
          } = this.props;

          const { address, longitude, latitude } = data;

          this.setState({
            dataLoading: false,
            metaData: data,
            mapAddress: address,
            mapLongitude: longitude,
            mapLatitude: latitude,
          });
        }
      });
    });
  };

  refitFieldDecoratorOption = (v, justice, defaultValue, originalOption) => {
    const result = originalOption;

    if (justice) {
      result.initialValue = v || (defaultValue || '');
    }

    return result;
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      location: { pathname },
    } = this.props;
    const { metaData } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        this.setState({ saving: true });
        const submitValue = values;
        submitValue.image = metaData.image;

        dispatch({
          type: 'saler/updateBasicInfo',
          payload: submitValue,
        }).then(() => {
          this.setState({ saving: false });
          const {
            saler: { data },
          } = this.props;
          const { code, message: messageText } = data;
          if (code === 200) {
            notification.success({
              placement: 'bottomRight',
              message: '操作结果',
              description: '数据已经保存成功，请进行后续操作。',
            });
          } else {
            notification.error({
              placement: 'bottomRight',
              message: '操作结果',
              description: messageText,
            });
          }

          dispatch(
            routerRedux.replace({
              pathname: `${pathname.replace('/load/', '/update/')}`,
            })
          );
        });
      }
    });
  };

  buildFieldDescription = (v, op, other) => {
    const o = (other || '') === '' ? '' : `,${other}`;
    return `请${op || '输入'}${v}${o}!`;
  };

  payTheFeesList = () => [{ flag: 0, name: '未缴费' }, { flag: 1, name: '已缴费' }];

  procurementList = () => [{ flag: 0, name: '关闭采购' }, { flag: 1, name: '开启采购' }];

  shopSwitchList = () => [{ flag: 0, name: '关闭店铺' }, { flag: 1, name: '开启店铺' }];

  deliverRegionList = () => {
    const { global } = this.props;
    return refitCommonData(global.deliverRegionList);
  };

  showList = () => [{ flag: 0, name: '不显示' }, { flag: 1, name: '显示' }];

  handleFormReset = () => {
    const { dispatch, form } = this.props;
    form.resetFields();
    dispatch({
      type: 'saler/getCurrent',
      payload: {},
    }).then(() => {
      const {
        saler: { data },
      } = this.props;
      this.setState({ metaData: data });
      this.setState({ saving: false });
    });
  };

  getErrorInfo = () => {
    const {
      form: { getFieldsError },
    } = this.props;
    const errors = getFieldsError();
    const errorCount = Object.keys(errors).filter(key => errors[key]).length;
    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = fieldKey => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = Object.keys(errors).map(key => {
      if (!errors[key]) {
        return null;
      }
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <Icon type="cross-circle-o" className={styles.errorIcon} />
          <div className={styles.errorMessage}>{errors[key][0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={trigger => trigger.parentNode}
        >
          <Icon type="exclamation-circle" />
        </Popover>
        {errorCount}
      </span>
    );
  };

  // resizeFooterToolbar = () => {
  //   requestAnimationFrame(() => {
  //     const sider = document.querySelectorAll('.ant-layout-sider')[0];
  //     if (sider) {
  //       const width = `calc(100% - ${sider.style.width})`;
  //       const { width: stateWidth } = this.state;
  //       if (stateWidth !== width) {
  //         this.setState({ width });
  //       }
  //     }
  //   });
  // };

  afterMapCreated = amapObject => {
    const { metaData } = this.state;
    const { latitude: latitudeData, longitude: longitudeData } = metaData;

    if (latitudeData > 0 && longitudeData > 0) {
      const point = new amapObject.LngLat(longitudeData, latitudeData);
      this.setPositionInfo(point);
    }
  };

  setPositionInfo = position => {
    const { metaData } = this.state;

    metaData.address = position.address;
    metaData.latitude = position.position.lat;
    metaData.longitude = position.position.lng;

    this.setState({
      mapAddress: position.address,
      mapLatitude: position.position.lat,
      mapLongitude: position.position.lng,
      // mapPosition: JSON.stringify(position),
      metaData,
    });
  };

  validate = () => {
    const {
      form: { validateFieldsAndScroll },
      dispatch,
      location: { pathname },
    } = this.props;
    const { metaData } = this.state;

    validateFieldsAndScroll((error, values) => {
      if (!error) {
        this.setState({ saving: true });
        const submitValue = values;
        submitValue.image = metaData.image;

        dispatch({
          type: 'saler/updateBasic',
          payload: submitValue,
        }).then(() => {
          const {
            saler: { data },
          } = this.props;
          const { code } = data;
          if (code === 200) {
            notification.success({
              placement: 'bottomRight',
              message: '操作结果',
              description: '数据已经保存成功，请进行后续操作。',
            });
          }

          this.setState({ saving: false }, () => {
            dispatch(
              routerRedux.replace({
                pathname: `${pathname.replace('/load/', '/update/')}`,
              })
            );
          });
        });
      }
    });
  };

  render() {
    const { form, dispatch } = this.props;
    const {
      metaData,
      saving,
      //  width,
      dataLoading,
      mapAddress,
      mapLatitude,
      mapLongitude,
    } = this.state;
    const { getFieldDecorator } = form;

    const payTheFeesData = this.payTheFeesList();
    const payTheFeesOption = [];

    payTheFeesData.forEach(item => {
      const { name, flag } = item;
      payTheFeesOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const procurementData = this.procurementList();
    const procurementOption = [];

    procurementData.forEach(item => {
      const { name, flag } = item;
      procurementOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const shopSwitchData = this.shopSwitchList();
    const shopSwitchOption = [];

    shopSwitchData.forEach(item => {
      const { name, flag } = item;
      shopSwitchOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const deliverRegionData = this.deliverRegionList();
    const deliverRegionOption = [];

    deliverRegionData.forEach(item => {
      const { name, flag } = item;
      deliverRegionOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const showData = this.showList();
    const showOption = [];

    showData.forEach(item => {
      const { name, flag } = item;
      showOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    return (
      <Fragment>
        <div className={styles.containorBox}>
          <Card
            title="站长基本信息"
            className={styles.card}
            bordered={false}
            extra={
              <Affix offsetTop={20}>
                {this.getErrorInfo()}
                <Button
                  type="primary"
                  icon="save"
                  disabled={dataLoading}
                  // onClick={this.handleSaveBasicInfo}
                  onClick={this.validate}
                  loading={saving}
                >
                  保存
                </Button>
              </Affix>
            }
          >
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical">
                <Row gutter={24}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.intuserid}>
                      {getFieldDecorator(
                        'intuserid',
                        refitFieldDecoratorOption(metaData.intuserid, metaData.intuserid, '', {
                          rules: [
                            {
                              required: false,
                            },
                          ],
                        })
                      )(<span>{metaData.intuserid}</span>)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.chvmname}>
                      {getFieldDecorator(
                        'chvmname',
                        refitFieldDecoratorOption(metaData.chvmname, metaData.chvmname, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.chvmname),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.chvmname)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.chvrealname}>
                      {getFieldDecorator(
                        'chvrealname',
                        refitFieldDecoratorOption(metaData.chvrealname, metaData.chvrealname, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.chvrealname),
                            },
                          ],
                        })
                      )(
                        <Input placeholder={this.buildFieldDescription(fieldLabels.chvrealname)} />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.phone}>
                      {getFieldDecorator(
                        'phone',
                        refitFieldDecoratorOption(metaData.phone, metaData.phone, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.phone),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.phone)} />)}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.emergencyPhone}>
                      {getFieldDecorator(
                        'emergencyPhone',
                        refitFieldDecoratorOption(
                          metaData.emergencyPhone,
                          metaData.emergencyPhone,
                          '',
                          {
                            rules: [
                              {
                                required: false,
                                message: this.buildFieldDescription(fieldLabels.emergencyPhone),
                              },
                            ],
                          }
                        )
                      )(
                        <Input
                          placeholder={this.buildFieldDescription(fieldLabels.emergencyPhone)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.idCard}>
                      {getFieldDecorator(
                        'idCard',
                        refitFieldDecoratorOption(metaData.idCard, metaData.idCard, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.idCard),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.idCard)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.bankName}>
                      {getFieldDecorator(
                        'bankName',
                        refitFieldDecoratorOption(metaData.bankName, metaData.bankName, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.bankName),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.bankName)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.creditCardNumber}>
                      {getFieldDecorator(
                        'creditCardNumber',
                        refitFieldDecoratorOption(
                          metaData.creditCardNumber,
                          metaData.creditCardNumber,
                          '',
                          {
                            rules: [
                              {
                                required: false,
                                message: this.buildFieldDescription(fieldLabels.creditCardNumber),
                              },
                            ],
                          }
                        )
                      )(
                        <Input
                          placeholder={this.buildFieldDescription(fieldLabels.creditCardNumber)}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </Card>
          <Card title="状态与设置" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical">
                <Row gutter={16}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.payTheFees}>
                      {getFieldDecorator(
                        'payTheFees',
                        refitFieldDecoratorOption(metaData.payTheFees, metaData.payTheFees, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.payTheFees),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(fieldLabels.payTheFees, '选择')}
                        >
                          {payTheFeesOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.procurement}>
                      {getFieldDecorator(
                        'procurement',
                        refitFieldDecoratorOption(metaData.procurement, metaData.procurement, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.procurement),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(
                            fieldLabels.procurement,
                            '选择是否'
                          )}
                        >
                          {procurementOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.shopSwitch}>
                      {getFieldDecorator(
                        'shopSwitch',
                        refitFieldDecoratorOption(metaData.shopSwitch, metaData.shopSwitch, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.shopSwitch),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(fieldLabels.shopSwitch, '选择')}
                        >
                          {shopSwitchOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.lineId}>
                      {getFieldDecorator(
                        'lineId',
                        refitFieldDecoratorOption(metaData.lineId, metaData.lineId, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.lineId),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(fieldLabels.lineId, '选择')}
                        >
                          {deliverRegionOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.show}>
                      {getFieldDecorator(
                        'show',
                        refitFieldDecoratorOption(metaData.show, metaData.show, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.show),
                            },
                          ],
                        })
                      )(
                        <Select placeholder={this.buildFieldDescription(fieldLabels.show, '选择')}>
                          {showOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </Card>
          <Card title="证件信息" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical">
                <Row gutter={16}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.frontPapersImage}>
                      {getFieldDecorator(
                        'frontPapersImage',
                        refitFieldDecoratorOption(
                          metaData.frontPapersImage,
                          metaData.frontPapersImage,
                          0,
                          {
                            rules: [
                              {
                                required: false,
                                message: this.buildFieldDescription(fieldLabels.frontPapersImage),
                              },
                            ],
                          }
                        )
                      )(
                        <div className={styles.papersBox}>
                          <img
                            src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542287589308&di=b245924a200e64cc6e7c3c7f21d3c58f&imgtype=0&src=http%3A%2F%2Fi0.hexun.com%2F2017-09-08%2F190777571.jpg"
                            alt={fieldLabels.frontPapersImage}
                          />
                        </div>
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.contraryPapersImage}>
                      {getFieldDecorator(
                        'contraryPapersImage',
                        refitFieldDecoratorOption(
                          metaData.contraryPapersImage,
                          metaData.contraryPapersImage,
                          0,
                          {
                            rules: [
                              {
                                required: false,
                                message: this.buildFieldDescription(
                                  fieldLabels.contraryPapersImage
                                ),
                              },
                            ],
                          }
                        )
                      )(
                        <div className={styles.papersBox}>
                          <img
                            src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542287744577&di=89a46fe49f426181396807eb2df4096a&imgtype=0&src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20161101%2F648b6fb72cc54e15ba5ea8f806a68d45_th.jpeg"
                            alt={fieldLabels.contraryPapersImage}
                          />
                        </div>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </Card>
          <Card title="所在地信息" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical">
                <Row gutter={16}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.area}>
                      {getFieldDecorator(
                        'area',
                        refitFieldDecoratorOption(metaData.area, metaData.area, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.area),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.area)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.address}>
                      <Input
                        placeholder={this.buildFieldDescription(fieldLabels.address)}
                        defaultValue={mapAddress}
                        value={mapAddress}
                        onChange={e => {
                          this.onChangeAddress(e);
                        }}
                      />
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.longitude}>
                      <Input
                        placeholder={this.buildFieldDescription(fieldLabels.longitude)}
                        defaultValue={mapLongitude}
                        value={mapLongitude}
                        readOnly
                        onChange={e => {
                          this.onChangeLongitude(e);
                        }}
                      />
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.latitude}>
                      <Input
                        placeholder={this.buildFieldDescription(fieldLabels.latitude)}
                        defaultValue={mapLatitude}
                        value={mapLatitude}
                        readOnly
                        onChange={e => {
                          this.onChangeLatitude(e);
                        }}
                      />
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col lg={24} md={24} sm={24}>
                    <FormItem label={fieldLabels.map}>
                      {getFieldDecorator(
                        'map',
                        refitFieldDecoratorOption(metaData.map, metaData.map, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.map),
                            },
                          ],
                        })
                      )(
                        <div className={styles.mapBox}>
                          <div className={styles.searchBox}>
                            <Input
                              className={styles.searchEl}
                              id="pickerInput"
                              placeholder="在此输入地址检索"
                              addonBefore="地址检索"
                            />
                          </div>
                          <div className={styles.mapInnerBox}>
                            <Map
                              amapkey="bff966857f8311eb68ea03dcbac869ad"
                              // version="1.4.6"
                              zoom="16"
                              useAMapUI
                              touchZoom
                              scrollWheel
                              zoomEnable
                              events={{
                                created: () => {
                                  dispatch({
                                    type: 'global/setAMapObject',
                                    payload: window.AMap,
                                  });
                                },
                              }}
                            >
                              <Geolocation {...pluginProps} />
                              <UIPoiPicker />
                              <UIPositionPicker callback={this.setPositionInfo} />
                            </Map>
                          </div>
                        </div>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </Card>
        </div>
        <BackTop />
      </Fragment>
    );
  }
}

export default BasicInfo;
